package com.cnh.framework.helper;

import com.cnh.framework.annotation.Inject;
import com.cnh.framework.util.ArrayUtil;
import com.cnh.framework.util.CollectionUtil;
import com.cnh.framework.util.ReflectionUtil;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * @author cnh
 * @create 2019-02-14 14:50
 * 说明：依赖注入助手类
 */
public final class IocHelper {
    static {
        //获取所有的Bean类与bean实例之间的映射关系（简称Bena Map）
        Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();

        if (CollectionUtil.isNotEmpty(beanMap)) {

            for (Map.Entry<Class<?>, Object> beanEntry : beanMap.entrySet()) {

                Class<?> beanClass = beanEntry.getKey();
                Object beanInstance = beanEntry.getValue();
                //获取bean类定义的所有成员遍历
                Field[] beanFields = beanClass.getDeclaredFields();

                if (ArrayUtil.isNotEmpty(beanFields)) {

                    for (Field beanField : beanFields) {

                        //判断当前Bean Field是否带有Inject注解
                        if (beanField.isAnnotationPresent(Inject.class)){
                            //从Bean Map 中获取Bean Filed对应的实例
                            Class<?> beanFieldClass = beanField.getType();
                            Object beanFieldInstance = beanMap.get(beanFieldClass);
                            if (beanFieldInstance != null){
                                //通过反射初始化Bean Field的值
                                ReflectionUtil.setField(beanInstance, beanField, beanFieldInstance);
                            }

                        }
                    }
                }

            }
        }
    }
}
